package store.lunangangster.engine.impl.cmd;

import store.lunangangster.engine.impl.interceptor.CommandInterceptor;

public class CommandExecutorImpl implements CommandExecutor {

  protected CommandInterceptor head;
  protected CommandInterceptor tail;

  public CommandExecutorImpl() {
  }

  public CommandExecutorImpl(CommandInterceptor head) {
    this.head = this.tail = head;
  }

  @Override
  public <T> T execute(Command<T> command) {
    if (head != null) {
      return head.execute(command);
    }
    return null;
  }

  @Override
  public void setHead(CommandInterceptor head) {
    this.head = head;
    this.tail = findTail(head);
  }

  private CommandInterceptor findTail(CommandInterceptor interceptor) {
    if (interceptor == null) {
      return null;
    }
    CommandInterceptor tail = interceptor;
    while (tail.hasNext()) {
      tail = tail.next();
    }
    return tail;
  }

  @Override
  public void addInterceptor(CommandInterceptor interceptor) {
    if (tail == null) {
      setHead(interceptor);
    } else {
      tail.setNext(interceptor);
      tail = interceptor;
    }
  }

}
